﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom;
using System.IO;
using Cow.Module;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace Cow
{
    public abstract class ExportFromCodeDom : IExportHandler
    {
        public virtual string PrefixName
        {
            get { return String.Empty; }
        }

        public virtual string SuffixName
        {
            get { return String.Empty; }
        }
        protected abstract CodeNamespace CreateCode(Design design);
        public void Export(Design design)
        {
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            compileUnit.Namespaces.Add(CreateCode(design));
            //目录不存在则创建
            var folder = Directory.GetParent(design.OutputPath);
            if (!folder.Exists)
            {
                folder.Create();
            }
            CSharpCodeProvider provider = new CSharpCodeProvider();
            using (StreamWriter sw = new StreamWriter(design.OutputPath, false))
            {
                IndentedTextWriter tw = new IndentedTextWriter(sw, "    ");
                provider.GenerateCodeFromCompileUnit(compileUnit, tw,
                    new CodeGeneratorOptions());
                tw.Close();
            }
        }
    }
}
